<template>
     <div class="app-container">
          <!-- <div>单价计算</div> -->
          <div class="btn-box">
               <el-button type="primary" @click="addRow">添加</el-button>
               <el-button type="success" @click="validateInputData">计算</el-button>
               <el-button type="primary" @click="addRow">导入</el-button>
               <el-button type="primary" @click="addRow">导出</el-button>
               <div class="exchangeRate">
                    外币汇率选择：
                    <el-select v-model="exchangeRate" placeholder="请选择汇率" style="width: 130px">
                         <el-option v-for="i in exchangeRateList" :key="i.value" :label="i.value" :value="i.value" />
                    </el-select>
               </div>
          </div>
          <div>
               <el-table v-loading="loading" :data="tableData" style="width: 100%" :height="maxHeight"
                    header-cell-class-name="hcellName" :cell-class-name="checkRowsName">
                    <el-table-column type="index" label="序列号" align="center" width="80" fixed="left" />
                    <el-table-column v-for="(item, index) in tableHeaderList" :key="item.prop" :prop="item.prop"
                         :label="item.label" align="center" :fixed="item.fixed" :width="item.width">
                         <template #header="{ column }">
                              <div v-if="item.prop == 'fob_price'"> FOB{{ exchangeRate.slice(0, 2) }}单价</div>
                              <div v-else>{{ column.label }}</div>
                         </template>
                         <template v-if="item.children">
                              <el-table-column v-for="(i, indexS) in item.children" :key="i.prop" :prop="i.prop"
                                   :label="i.label" align="center" :fixed="i.fixed" :width="i.width">
                                   <template #default="scope">
                                        <template v-if="i.prop == 'core_glue_code'">
                                             <el-select v-model="scope.row.core_glue_code"
                                                  @change="changeCode($event, scope.row)" size="small"
                                                  style="width: 80px">
                                                  <el-option v-for="i in codeOption" :key="i.code" :label="i.code"
                                                       :value="i.code" />
                                             </el-select>
                                        </template>
                                        <template v-else-if="i.prop == 'cover_glue_code'">
                                             <el-select v-model="scope.row.cover_glue_code"
                                                  @change="changeCoverCode($event, scope.row)" size="small"
                                                  style="width: 80px">
                                                  <el-option v-for="i in codeOption" :key="i.code" :label="i.code"
                                                       :value="i.code" />
                                             </el-select>
                                        </template>
                                        <el-input-number v-else-if="i.type == 'el-input-number'"
                                             v-model="scope.row[i.prop]" :controls="false" size="small"
                                             style="width: 80px" />

                                        <div v-else>{{ scope.row[i.prop] }}</div>
                                   </template>
                              </el-table-column>

                         </template>
                         <template v-if="!item.children" #default="scope">
                              <div v-if="item.prop === 'model'">
                                   <el-select v-model="scope.row[item.prop]" @change="changeModel($event, scope.row)"
                                        placeholder="请选择规格型号" size="small" style="width: 130px">
                                        <el-option v-for="i in options" :key="i.formMame" :label="i.formMame"
                                             :value="i.formMame" />
                                   </el-select>
                              </div>
                              <div v-else-if="item.type == 'el-input-number'">
                                   <el-input-number v-model="scope.row[item.prop]" :controls="false" size="small"
                                        style="width: 80px" />
                              </div>
                              <div v-else-if="item.type == 'el-input'">
                                   <el-input v-model="scope.row[item.prop]" size="small" style="width: 80px" />
                              </div>
                              <div v-else>{{ scope.row[item.prop] }}</div>
                         </template>

                    </el-table-column>
                    <el-table-column prop="opt" label="操作" width="60" align="center" fixed="right">
                         <template #default="scope">
                              <el-link type="danger" @click="deleteRow(scope.row, scope.$index)">删除</el-link>
                         </template>
                    </el-table-column>
               </el-table>
          </div>
     </div>
</template>
<script setup>
import { translate } from '../../api/public'
import { ElMessage, ElMessageBox } from 'element-plus';
import { tableHeaderList } from './data'
import { onMounted } from 'vue';
const tableData = ref([])
const loading = ref(false)
const exchangeRate = ref('美元7.2')// 汇率
const exchangeRateList = ref([{
     label: '美元',
     value: '美元7.2'
}, {
     label: '英镑',
     value: '英镑9.2'
}, {
     label: '卢布',
     value: '卢布0.0722'
}])
const checkRows = ref([])
function checkRowsName(data) {
     let cellName = 'cellName'
     if (checkRows.value.length != 0) {
          const findObj = checkRows.value.find(item => {
               return item.index == data.rowIndex + 1
          })
          if (findObj) {
               const findi = findObj.data.find(item => {
                    return item == data.column.property
               })
               if (findi) {
                    cellName += ' cellName-error'
               }
          }
     }
     return cellName
}
const validateInputData = () => {
     checkRows.value = []
     const missingRows = [];
     const calculateRow = []
     let needInputData = getNeedInputData()
     tableData.value.forEach((row, index) => {
          let arr = []
          needInputData.forEach(key => {
               if (row[key] === undefined || row[key] == '' || row[key] == null) {
                    arr.push(key)
               }
          });
          if (arr.length > 0) {
               let obj = {
                    index: index + 1,
                    data: arr
               }
               missingRows.push(obj); // 记录缺少值的行号
               checkRows.value.push(obj)
          } else {
               calculateRow.push(index)
          }
     });

     if (missingRows.length > 0) {
          const indexArr = missingRows.map(obj => obj.index);
          ElMessage.error(`请检查第${indexArr.join(', ')}行的输入值 `);
          console.log(checkRows.value)
     }
     if (calculateRow.length !== 0) {
          calculate(calculateRow);
     }
};

/**
 * @description: 每行计算
 * @param {*} calculateRow 需要计算的行号
 */
const calculate = (calculateRow) => {
     loading.value = true
     setTimeout(() => {
          let arr = []
          tableData.value.forEach((row, index) => {
               if (calculateRow.includes(index)) {
                    // 计算逻辑
                    // 总厚度
                    row.total_thickness = Number(row.core_thickness + row.upper_glue_thickness + row.lower_glue_thickness)
                    // 宽度英寸 转 宽度毫米
                    row.width_mm = Number(row.width_inch) * 25.4
                    // 卷数
                    row.roll_count = Number(row.total_length) / Number(row.length_per_roll)
                    // 每卷理论直径
                    row.theoretical_diameter = Number(Math.sqrt((1.273237 * (row.total_thickness / 1000) * row.length_per_roll) + 0.9).toFixed(2));
                    if (row.theoretical_diameter >= 2.3) {
                         arr.push(index + 1)
                    }
                    //每卷重量
                    row.roll_weight = Number((row.length_per_roll * 10 * row.total_thickness / 100 * row.width_mm / 100 * 1.32 + row.width_mm / 100 * 5).toFixed(2))
                    // 每英寸重量
                    row.weight_per_inch_m = Number((row.roll_weight / row.length_per_roll / row.width_inch).toFixed(3))
                    //包/切边宽m
                    row.edge_width = Number((row.width_mm + 40) / 1000)
                    // 芯胶厚
                    row.core_glue_thickness = Number((row.core_thickness / row.layers))
                    // 上胶量 芯胶厚向上保留一位小数之后去查 上胶量表格中查找
                    const coreCount = Math.ceil(row.core_glue_thickness * 10) / 10
                    const list = options.value.find(option => option.specifications === row.specifications)
                    const obj = list.list.find(item => Number(item.thickness) === coreCount)
                    row.upper_glue_amount = Number(obj.amount)
                    //工费元/㎡
                    row.labor_price = Number(row.labor_cost * (row.layers + (row.upper_glue_thickness + row.lower_glue_thickness) / 1.5))
                    // 芯胶布原元/㎡
                    row.core_glue_material_price = Number(((row.weight * row.unitPrice + row.core_glue_price * row.upper_glue_amount) * row.layers).toFixed(3))
                    //盖胶原元/㎡
                    row.cover_glue_material_price = Number(((row.upper_glue_thickness + row.lower_glue_thickness) * 1.2 * row.cover_glue_price))
                    //单价元/㎡
                    row.unit_price = Number(((row.labor_price + row.core_glue_material_price + row.cover_glue_material_price) * row.edge_width * 1.02).toFixed(8))
                    //FOB美元单价
                    row.fob_price = Number(roundUp(row.unit_price / 7, 2))
                    //小计
                    row.subtotal = Number(row.fob_price * row.length_per_roll)
               }
          });
          loading.value = false
          if (arr.length > 0) {
               ElMessage({
                    showClose: true,
                    message: `第${arr.join(', ')}行的每卷理论直径大于2.3，请检查！ `,
                    type: 'error',
                    duration: '5000'
               })
          }
     }, 2000)
}
function roundUp(num, decimalPlaces) {
     if (decimalPlaces < 0) {
          throw new Error("Decimal places must be non-negative");
     }
     const factor = Math.pow(10, decimalPlaces);
     return Math.ceil(num * factor) / factor;
}

// 选择规格型号
const changeModel = (value, row) => {
     // 找到选中的选项
     const selectedOption = options.value.find(option => option.formMame === value)
     if (selectedOption) {
          // 将选中选项的data数据合并到当前行
          Object.assign(row, selectedOption)
     }
}
//
function changeCode(value, row) {
     // 找到选中的选项
     const selectedOption = codeOption.value.find(option => option.code === value)
     row.core_glue_price = selectedOption.coreAdhesivePrice
}
function changeCoverCode(value, row) {
     // 找到选中的选项
     const selectedOption = codeOption.value.find(option => option.code === value)
     row.cover_glue_price = selectedOption.coverGluePrice
}
function addRow() {
     tableData.value.push(generateTableData())
}
function deleteRow(row, index) {
     ElMessageBox.confirm('是否删除该条数据?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
     }).then(() => {
          // 删除数据
          tableData.value.splice(index, 1);
     }).catch(() => { });
}
const generateTableData = () => {
     let row = {};
     tableHeaderList.forEach(header => {
          row[header.prop] = ''; // 初始化每个属性为空
          if (header.children) {
               header.children.forEach(child => {
                    row[child.prop] = ''; // 初始化子属性为空
               });
          }
          row.layers = 2
          row.core_thickness = 2.3
          row.upper_glue_thickness = 3
          row.lower_glue_thickness = 1.5
          row.width_inch = 18
          row.length_per_roll = 400
          row.total_length = 800
          row.labor_cost = 3
     });
     return row;
};
const getNeedInputData = () => {
     let row = [];
     tableHeaderList.map(header => {
          if (header.type == 'el-input' || header.type == 'el-input-number' || header.type == 'select') {
               row.push(header.prop)
          }
          if (header.children) {
               header.children.forEach(child => {
                    if (child.type == 'el-input' || child.type == 'el-input-number' || child.type == 'select') {
                         row.push(child.prop)
                    }
               });
          }
     });
     row = row.filter(item => item !== 'production_number');
     return row;
};
const options = ref([{
     formMame: 'EP250/2',
     specifications: '125',
     weight: '0.44',
     canvasThickness: '0.5',
     unitPrice: '18',
     list: [{
          thickness: '1',
          amount: '0.844'
     }, {
          thickness: '1.2',
          amount: '0.95'
     }]

}, {
     formMame: 'EP375/3',
     specifications: '125',
     weight: '0.44',
     canvasThickness: '0.6',
     unitPrice: '18',
     list: [{
          thickness: '1',
          amount: '0.844'
     }, {
          thickness: '1.1',
          amount: '0.844'
     }, {
          thickness: '1.2',
          amount: '0.844'
     }, {
          thickness: '1.3',
          amount: '0.844'
     }]

}])
const codeOption = ref([
     {
          code: 'A',
          coreAdhesivePrice: '4.32',
          coverGluePrice: '4.69'
     },
     {
          code: 'B',
          coreAdhesivePrice: '7.73',
          coverGluePrice: '4.69'
     }
])
const maxHeight = ref(600)
onMounted(() => {
     let row = generateTableData()
     console.log("🚀 ~ onMounted ~ row:", row)
     tableData.value.push(row)
     maxHeight.value = document.documentElement.clientHeight - 150;
})
</script>
<style lang="scss" scoped>
.btn-box {
     display: flex;
     margin: 10px 20px;
     // justify-content: flex-end;
}

.exchangeRate {
     font-size: 14px;
     margin: 0 20px;
}

:deep(.hcellName) {
     padding: 0;
     font-size: 14px;
     font-weight: bold;
     color: #000;
}

:deep(.cellName) {
     padding: 5px 0;

     .cell {
          padding: 0;
     }
}

:deep(.cellName-error) {
     background-color: rgb(196, 86.4, 86.4) !important;

}
</style>